package cn.tqfeiyang.springplus.framework.security.loader;

import cn.tqfeiyang.springplus.framework.Constants;
import cn.tqfeiyang.springplus.framework.security.AuthenticationUserDetails;
import cn.tqfeiyang.springplus.framework.security.AuthenticationUserLoader;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

public class InMemoryAuthenticationUserLoader implements AuthenticationUserLoader {

    final static List<AuthenticationUserDetails> userList;

    static {
        userList = new ArrayList<>();

        // 管理员，admin / 123456
        AuthenticationUserDetails adminUser = new AuthenticationUserDetails();
        adminUser.setId(1L);
        adminUser.setUsername("admin");
        adminUser.setPassword("$2a$10$eWNnKfuvcJ4YeOq28ZCRO.0FxsrdZ6daD7IZHgmzZW3rOIiGdRAh.");
        adminUser.setUuid("3e48d184-22a1-4f9f-a321-05dc3483d29c");
        adminUser.getRoles().add(Constants.ROLE_ADMIN);
        userList.add(adminUser);

        // 测试账号，test / 123456
        AuthenticationUserDetails testUser = new AuthenticationUserDetails();
        testUser.setId(2L);
        testUser.setUsername("test");
        testUser.setPassword("$2a$10$dnIIDE1nQ8BeUpfjB/8HseP6wZlLRt6etRdUVPNEsC4B/q2KM/Bwe");
        testUser.setUuid("5d72975f-50be-4f04-9604-548902441a3f");
        userList.add(testUser);
    }

    @Bean

    public AuthenticationUserLoader authenticationUserLoader() {
        return new InMemoryAuthenticationUserLoader();
    }

    @Override
    public AuthenticationUserDetails loadByUsername(String username) {
        return userList.stream()
                .filter(t -> t.getUsername().equalsIgnoreCase(username))
                .findFirst().orElse(null);
    }

    @Override
    public AuthenticationUserDetails loadByUUID(String uuid) {
        return userList.stream()
                .filter(t -> t.getUuid().equalsIgnoreCase(uuid))
                .findFirst().orElse(null);
    }
}
